import 'dart:io';
import 'package:FineArt/components/horizon_scroll.dart';
import 'package:FineArt/components/rounded_text.dart';
import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/material_api.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/api/resource_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/core/widget/grid/grid_item.dart';
import 'package:FineArt/core/widget/grid/grid_item_photo.dart';
import 'package:FineArt/core/widget/grid/grid_item_teach.dart';
import 'package:FineArt/core/widget/grid/grid_staggered_item_photo.dart';
import 'package:FineArt/core/widget/list/article_item.dart';
import 'package:FineArt/page/imageview/AgencyImagePreview.dart';
import 'package:FineArt/page/imageview/BookPreview.dart';
import 'package:FineArt/page/imageview/LargePhotoView.dart';
import 'package:FineArt/page/imageview/RoundCheckBox.dart';
import 'package:FineArt/page/imageview/TeacherCourseView.dart';
import 'package:FineArt/page/tab/CreateFolder.dart';
import 'package:FineArt/page/tab/recommend/component/recommendItem.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:image_picker/image_picker.dart';

/**
 * 校园素材
 */
class PublicMaterialFolderPage extends StatefulWidget {
  PublicMaterialFolderPage();

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _PublicMaterialFolderState();
  }
}

class _PublicMaterialFolderState extends State<PublicMaterialFolderPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    buildAddItem();
    _getFolder();
  }

  int _pId = 0;
  int level = 1;
  int _lastFolderId = 0;
  FileDirBean _lastFb;
  bool isLoadedFolder = false;
  List<int> pidArr = [];

  int currentPage = 0;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    LogUtil.d("didChangeDependencies>>>>>>");
    //   if(isLoadedFolder)
    //   _getFiles();
  }

  @override
  void didUpdateWidget(StatefulWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    LogUtil.d("didUpdateWidget>>>>>>");
  }

  _getFolder() {
    LogUtil.d("getFolder>>>");
    MaterialApi().getDir("PUBLIC", _lastFolderId).then((result) {
      if (result.code == 200) {
        serverFolderCount = result.data.length;
        allFolders = result.data;
        setState(() {
          currentFolderFile.clear();
          for (int i = 0; i < result.data.length; i++) {
            FileDirBean dir = result.data[i];
            FolderBean fb =
                FolderBean(folderAssetsUrl, dir.label, dir.id.toString());
            fb.dir = dir;
            currentFolderFile.add(fb);
          }
        });
        LogUtil.d("getFolder len>>>${currentFolderFile.length}");
        currentPage = 0;
        _getFiles();
        isLoadedFolder = true;
      }
    });
  }

  _reLoadCurFolder(List<FileDirBean> fbList) {
    setState(() {
      currentFolderFile.clear();
      if (fbList != null) {
        for (int i = 0; i < fbList.length; i++) {
          FileDirBean dir = fbList[i];
          FolderBean fb =
              FolderBean(folderAssetsUrl, dir.label, dir.id.toString());
          fb.dir = dir;
          currentFolderFile.add(fb);
        }
      }
      buildAddItem();
      LogUtil.d("_reLoadCurFolder len>>>${currentFolderFile.length}");
    });
  }

  //返回上级目录
  _getPreFolderByPid() {
    FileDirBean targetFb = _lastFb;
    //获取父级的同级兄弟
    LogUtil.d("_getPreFolderByPid pid  $pid");
    // if (targetFb != null) {
    //   _lastFolderId = targetFb.pId;
    //   bool existSuperPar;
    //   List<FileDirBean> fbList = [];
    //   LogUtil.d("targetFb pid  $pid");
    //   for (int i = 0; i < allFolders.length; i++) {
    //     FileDirBean par = _getFolderBeanByPid(targetFb.pId, allFolders[i]);
    //     if (par != null) {
    //       fbList.add(par);
    //     }
    //     LogUtil.d("targetFb 00  $par $i");
    //   }
    //   LogUtil.d("targetFb 011  $existSuperPar fbList.length ${fbList.length}");
    //   if (_lastFolderId > -1) {
    //     for (int i = 0; i < allFolders.length; i++) {
    //       FileDirBean fdb =
    //           _getParentFolderBeanById(_lastFolderId, allFolders[i]);
    //       if (fdb != null) {
    //         _pId = fdb.pId;
    //         _lastFb = fdb;
    //         break;
    //       }
    //     }
    //   }
    //   if (existSuperPar == null && fbList.length > 0) {
    //     LogUtil.d("targetFb _pId  $_pId _lastFolderId $_lastFolderId");
    //     _reLoadCurFolder(fbList);
    //   }
    // } else {
    //   LogUtil.d("targetFb null");
    // }
    // _getFiles();
    _lastFolderId = pidArr.removeLast();
    _getFolder();
  }

  FileDirBean _getFolderBeanByPid(int pid, FileDirBean fb) {
    LogUtil.d("_getFolderBeanByPid begin  ${fb.pId}>>$pid>>>>");
    if (fb.pId == pid) {
      return fb;
    }
    if (fb.children == null || fb.children.length == 0) return null;
    for (int i = 0; i < fb.children.length; i++) {
      FileDirBean tmp = _getFolderBeanByPid(pid, fb.children[i]);
      if (tmp != null) {
        return tmp;
      }
    }
    return null;
  }

  FileDirBean _getParentFolderBeanById(int pid, FileDirBean fb) {
    LogUtil.d("_getFolderBeanByPid begin  ${fb.id}>>$pid>>>>");
    if (fb.id == pid) {
      return fb;
    }
    FileDirBean tfb;
    if (fb.children == null || fb.children.length == 0) return null;
    for (int i = 0; i < fb.children.length; i++) {
      tfb = _getParentFolderBeanById(pid, fb.children[i]);
      if (tfb != null) {
        break;
      }
    }
    return tfb;
  }

  _getFiles() {
    LogUtil.d("_getFiles begin  ${currentFolderFile.length}>>>>>>");
    MaterialApi()
        .fileList(_lastFolderId, currentPage, PAGE_SIZE)
        .then((result) {
      if (result.code == 200) {
        int len = result.data.list.length;
        LogUtil.d("_getFiles len 00  $len>>>>>>");
        List<FolderBean> fList = [];
        for (int i = 0; i < len; i++) {
          FileEntity file = result.data.list[i];
          FolderBean fb =
              FolderBean(file.urlThumb, file.name, file.id.toString());
          fb.file = file;
          fb.isFile = true;
          fList.add(fb);
        }
        if (fList.length > 0) {
          setState(() {
            for (int i = 0; i < currentFolderFile.length; i++) {
              FolderBean fb = currentFolderFile[i];
              if (fb.isFile) {
                currentFolderFile.removeAt(i);
                i--;
              }
            }
            currentFolderFile.addAll(fList);
          });
        }

        currentPage = result.data.pageIndex + 1;

        LogUtil.d("_getFiles ${currentFolderFile.length}>>>>>>");
      }
    });
  }

  Future<bool> _requestPop() {
    print("_requestBack $_pId");
    level--;
    if (level > 0) {
      LogUtil.d("返回上一文件夹");

      _getPreFolderByPid();
      return Future.value(false);
    }

    print("_requestBack111");
    if (Navigator.canPop(context)) {
      Navigator.pop(context);
    } else {
      SystemNavigator.pop();
    }
    return Future.value(false);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    var width = MediaQuery.of(context).size.width * 0.76;
    return WillPopScope(
      onWillPop: _requestPop,
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            "校园素材",
            style: TextStyle(color: text_black, fontSize: setSp(18)),
          ),
          backgroundColor: Colors.white,
          centerTitle: true,
          brightness: Brightness.light,
          iconTheme: IconThemeData(
            color: text_black, //修改颜色
          ),
          elevation: 0,
          actions: <Widget>[],
        ),
        body: Column(
          children: [
            Expanded(child: _buildRefreshGridView()),
            // Padding(
            //     padding: EdgeInsets.symmetric(
            //         vertical: 0, horizontal: getPortraitSWidth(16)),
            //     child: Column(
            //       children: [
            //         Expanded(child: _buildRefreshGridView()),
            //       ],
            //     )),
          ],
        ),
      ),
    );
  }

  bool loading = false;

  Widget _buildRefreshGridView() {
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 100));
    return EasyRefresh.custom(
      header: header,
      footer: MaterialFooter(),
      onRefresh: () async {
        _getFolder();
      },
      onLoad: () async {
        if (loading) return;
        loading = true;
        new Future.delayed(Duration(seconds: 1), () {
          loading = false;
          _getFiles();
        });
      },
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: RefreshIndicator(
            onRefresh: () async {
              // _getFolder();
            },
            child: Padding(
              padding: const EdgeInsets.only(top: 2, left: 4, right: 4),
              child: _buildGridView(),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildGridView() {
    double width = MediaQuery.of(context).size.width * 0.98;
    return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3, //每行三列
          childAspectRatio: 1.0, //显示区域宽高相等
          crossAxisSpacing: 3.0,
          // 定义行边距
          mainAxisSpacing: 3.0,
        ),
        shrinkWrap: true,
        itemCount: currentFolderFile.length,
        controller: new ScrollController(),
        itemBuilder: (context, index) {

          return getFolderItem(index, () {
            LogUtil.d("item click $index");
            FolderBean fb = currentFolderFile[index];
            if (fb.isFile) {
              //文件的跳转 todo
              // Resource resource =
              //     new Resource(type: 1, id: fb.file.id);
              // TeacherCourseView.Jump2CourseView(
              //     fb.file.urlSource, fb.file.id, context);

              List<AgencyResource> fs = [];
              int idx = 0;
              for (FolderBean item in currentFolderFile) {
                if (item.isFile) {
                  AgencyResource fr = new AgencyResource(
                      resid: item.file.id,
                      restype: int.parse(fb.file.type),
                      url: fb.file.urlThumb,
                      title: fb.file.name);
                  fs.add(fr);
                  if (fr.resid == fb.file.id) {
                    idx = fs.length - 1;
                  }
                }
              }
              AgencyImagePreview.JumpToPreview(
                  0, idx, fs, context, _lastFolderId);
            } else if (fb.dir != null) {
              //进入下一级目录
              _lastFb = fb.dir;
              _pId = fb.dir.pId;
              _lastFolderId = fb.dir.id;
              pidArr.add(_pId);
              level++;
              _getFolder();
              // _reLoadCurFolder(_lastFb.children);
              // _getFiles();
            }

            // List<FolderBean> tmpAct = actions;
            // if (index == actions.length - 1) {
            //   for (int i = 0; i < tmpAct.length; i++) {
            //     tmpAct[i].isCheck = false;
            //   }
            //   ToastUtils.toast("添加");
            // } else {
            //   for (int i = 0; i < tmpAct.length; i++) {
            //     tmpAct[i].isCheck = index == i ? true : false;
            //   }
            // }
            // setState(() {
            //   actions = tmpAct;
            // });
          });
        });
  }

  int serverFolderCount = 1;

// 返回每个隐藏的菜单项
  SelectView(IconData icon, String text, String id) {
    return new PopupMenuItem<String>(
        value: id,
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new Icon(icon, color: text_black),
            new Text(text),
          ],
        ));
  }

  Widget getFolderItem(int index, Function onTab) {
    FolderBean fd = currentFolderFile[index];
    if (fd.name == null) {
      fd.name = "默认";
    }

    return InkWell(
        onTap: onTab,
        child: Container(
          child: Stack(alignment: Alignment.center, children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                fd.isFile
                    ? Image(
                        fit: BoxFit.cover,
                    width: getPortraitSWidth(80),
                    height: getPortraitSHeight(90),
                        image: CachedNetworkImageProvider(
                          fd.imageUrl,
                        ))
                    : Image.asset(
                        fd.imageUrl,
                        width: getPortraitSWidth(59.5),
                      ),
                SizedBox(
                  height: 5,
                ),
                getItemBottomText(fd.isFile, fd.name)
                // isAdd
                //     ? SizedBox(
                //         height: 12,
                //       )
                //     : Text(
                //         fd.name ?? "默认",
                //         textAlign: TextAlign.center,
                //         style: TextStyle(
                //             color: text_black, fontSize: setSp(12), height: 1),
                //       )
              ],
            ),
            Positioned(
                bottom: getPortraitSHeight(30),
                right: 10,
                child: currentFolderFile[index].isCheck
                    ? RoundCheckBox(
                        value: true, isRadio: true, onChanged: (bool val) {})
                    : Text("")),
          ]),
        ));
  }

  Widget getItemBottomText(bool isFile, String name) {
    if (isFile) {
      name = "";
    }
    return Text(
      name ?? "默认",
      textAlign: TextAlign.center,
      style: TextStyle(color: text_black, fontSize: setSp(12), height: 1),
    );
  }

  List<FileDirBean> allFolders = [];
  List<FolderBean> currentFolderFile = [];
  String folderAssetsUrl = "assets/images/icon_folder.png";
  String addAssetsUrl = "assets/images/icon_add_black.png";

  void buildAddItem() {
    LogUtil.d("buildAddItem ${currentFolderFile.length}");
  }
}

class FolderBean {
  FileDirBean dir;
  FileEntity file;
  String imageUrl;
  String name;
  String id;
  bool isCheck = false;
  bool isFile = false;

  FolderBean(this.imageUrl, this.name, this.id);
}
